﻿using ALEXBlog.Entity;
using Microsoft.IdentityModel.Tokens;
using System;
using System.Collections.Generic;
using System.IdentityModel.Tokens.Jwt;
using System.Linq;
using System.Security.Claims;
using System.Text;
using System.Text.RegularExpressions;

namespace ALEXBlog.Helper
{
    public static class JwtHelperParamas
    {
        public static string SecretKey { get; set; } = "Chenlong1226550632";
        public static string Issuer { get; set; } = "www.lothric.icu";
    }
    public class TokenHelper
    {
        TimeSpan expires { get; set; } = new TimeSpan(hours: 12, minutes: 0, seconds: 0);
        public string TakeToken(TokenModel tokenModel)
        {
            DateTime UTC = DateTime.UtcNow;

            var claims = new List<Claim>
            {
                new Claim(JwtRegisteredClaimNames.Jti, tokenModel.Id.ToString()),//JWT ID,JWT的唯一标识
                new Claim(JwtRegisteredClaimNames.Iat, UTC.ToString(), ClaimValueTypes.Integer64),//Issued At，JWT颁发的时间，采用标准unix时间，用于验证过期
                new Claim(JwtRegisteredClaimNames.Iss,JwtHelperParamas.Issuer)
            };
            claims.AddRange(new RoleHelper(tokenModel).Roles.Select(s => new Claim(ClaimTypes.Role, s)));

            JwtSecurityToken jwt = new JwtSecurityToken(
                issuer: JwtHelperParamas.Issuer,//jwt签发者,非必须
                                                //audience:tokenModel.Name,//jwt的接收该方，非必须
                claims: claims, //声明合集
                expires: UTC.Add(expires),//绝对过期 指定token的生命周期，unix时间戳格式,非必须
                signingCredentials: new SigningCredentials(new SymmetricSecurityKey(Encoding.UTF8.GetBytes(JwtHelperParamas.SecretKey)), SecurityAlgorithms.HmacSha256)
                );

            var encodeJwt = new JwtSecurityTokenHandler().WriteToken(jwt);
            return encodeJwt;
        }

        public static TokenModel SerializeJwt(string jwtStr)
        {
            var jwtHandler = new JwtSecurityTokenHandler();
            JwtSecurityToken jwtToken = jwtHandler.ReadJwtToken(jwtStr);
            object role;
            try
            {
                jwtToken.Payload.TryGetValue(ClaimTypes.Role, out role);
                role = Regex.Replace(role.ToString(), @"[][]|[^,a-zA-z]", "");
            }
            catch (Exception e)
            {
                Console.WriteLine(e);
                throw;
            }
            var tm = new TokenModel
            {
                Id = Guid.Parse(jwtToken.Id),
                Role = role != null ? role.ToString() : "",
            };
            return tm;
        }

    }
}
